package com.dianrui.qiyouriding.activity;

import android.app.ProgressDialog;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import com.blankj.utilcode.util.SPUtils;
import com.dianrui.qiyouriding.Constant;
import com.dianrui.qiyouriding.MyApplication;
import com.dianrui.qiyouriding.R;
import com.dianrui.qiyouriding.bean.NewMobile;
import com.dianrui.qiyouriding.okhttp.OkHttpRequest;
import com.dianrui.qiyouriding.util.AESCBCUtils;
import com.dianrui.qiyouriding.util.MD5;
import com.dianrui.qiyouriding.util.RSAUtils;
import com.dianrui.qiyouriding.util.StringUtils;
import com.dianrui.qiyouriding.util.ToastUtil;
import com.dianrui.qiyouriding.util.Url;
import com.dianrui.qiyouriding.view.CountDownButton;
import com.google.gson.JsonObject;

import org.greenrobot.eventbus.EventBus;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.Random;

import butterknife.BindView;
import butterknife.OnClick;

@SuppressWarnings("ALL")
public class ShowMobileModiftyActivity extends BaseActivity {
    private String mCode;

    @BindView(R.id.title)
    TextView title;
    @BindView(R.id.et_mobile_new)
    EditText etMobileNew;
    @BindView(R.id.change)
    Button change;
    @BindView(R.id.et_code)
    EditText etCode;
    @BindView(R.id.get_code)
    CountDownButton getCode;


    @Override
    public int getContentViewId() {
        return R.layout.activity_showmobilemodifty;
    }

    @Override
    public void initView() {
        customInit(true,R.color.main_color);
        title.setText(getString(R.string.mobile_update));
        getCode.setOnOperationCallBack(new CountDownButton.CountDownButtonOperationCallBack() {
            @Override
            public void onFinish() {
                getCode.setText(getString(R.string.getcode_txt));
            }

            @Override
            public void onTick(long millisUntilFinished, CountDownButton countDownButton) {
                getCode.setText(getString(R.string.getcode_txt1) + millisUntilFinished / 1000 + getString(R.string.getcode_txt2));
            }

            @Override
            public void onClickFromUser(boolean isRunning, long millisUntilFinished, CountDownButton countDownButton) {
                ToastUtil.showToast( getString(R.string.getcode_txt3) + millisUntilFinished / 1000 + getString(R.string.getcode_txt4));
            }
        });

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (getCode != null) {
            getCode.destroy();
            getCode.cancel();
        }
    }

    @Override
    public void initData() {}


    @OnClick({R.id.back,R.id.get_code,R.id.change})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.back:
                finish();
                break;
            case R.id.get_code:
                if (StringUtils.isEmpty(etMobileNew.getText().toString().trim())) {
                    ToastUtil.showToast(getString(R.string.please_input_mobile));
                }else {
                    getCode();
                }
                break;
            case R.id.change:
                if (StringUtils.isEmpty(etMobileNew.getText().toString().trim())) {
                    ToastUtil.showToast(getString(R.string.please_input_mobile));
                } else if (StringUtils.isEmpty(etCode.getText().toString().trim())) {
                    ToastUtil.showToast(getString(R.string.please_input_mobiles));
                }else {
                    setInfoMobile();
                }
                break;

                default:
                    break;

        }
    }

    private void getCode() {
        showLoadingDialog("正在发送短信中...");
        JsonObject jsonObject=new JsonObject();
        JsonObject jsonObject1 = new JsonObject();
        jsonObject1.addProperty("account",etMobileNew.getText().toString());
        jsonObject1.addProperty("type","2");

        jsonObject.addProperty("content",  getMd5(jsonObject1.toString()));
        OkHttpRequest.getInstance().postRequests(Url.GETCODE, jsonObject.toString(), new OkHttpRequest.XCallBack() {
            @Override
            public void onResponse(String result) {
                if (!StringUtils.isEmpty(result)) {
                    try {
                        final JSONObject jsonObject = new JSONObject(result);
                        if (null != jsonObject &&!isFinishing()) {
                            if (Constant.DATASUCCESS.equals(jsonObject.optString("status"))) {
                                dismissLoadingDialog();
                                getCode.start();
                                ToastUtil.showToast(jsonObject.optString("message"));
                                mCode = jsonObject.optJSONObject("data").optString("code");
                            } else {
                                dismissLoadingDialog();
                                getCode.cancel();
                                getCode.setText(getString(R.string.getcode_txt));
                                ToastUtil.showToast(jsonObject.optString("message"));
                            }
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }

                }
            }

            @Override
            public void failedRequest(String result) {
                dismissLoadingDialog();
                ToastUtil.showToast(getString(R.string.net_error));
            }
        });
    }


    //设置新的手机号
    private void setInfoMobile() {
        JsonObject jsonObject = new JsonObject();
        jsonObject.addProperty("member_id", SPUtils.getInstance().getString("member_id"));
        jsonObject.addProperty("mobile", etMobileNew.getText().toString());
        jsonObject.addProperty("verify_code",etCode.getText().toString());
        OkHttpRequest.getInstance().postRequests(Url.SETINFO, jsonObject.toString(),  new OkHttpRequest.XCallBack() {

            @Override
            public void onResponse(String result) {
                if (!StringUtils.isEmpty(result)) {
                    try {
                        final JSONObject jsonObject = new JSONObject(result);
                        if (null != jsonObject &&!isFinishing()) {
                            if (Constant.DATASUCCESS.equals(jsonObject.optString("status"))) {
                                ToastUtil.showToast(jsonObject.optString("message"));
                                SPUtils.getInstance().clear();
                                MyApplication.initJiGuangUser("dsgfdbhfgh", ShowMobileModiftyActivity.this);
                                EventBus.getDefault().post(new NewMobile(jsonObject.optJSONObject("data").optString("mobile")));
                                JumpKillActivitys(LoginActivity.class);
                                finish();
                            } else {
                                ToastUtil.showToast(jsonObject.optString("message"));
                            }
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
            }

            @Override
            public void failedRequest(String result) {

            }
        });
    }

    public static  String getMd5(String json){
        String aes_key = getSeqNo(16);
        //rsa公钥
        String default_rsa_public_key =Constant.RAS;
        String plantText = json;
        String aes_str = AESCBCUtils.encrypt(plantText, aes_key); //aes密文
        String rsa_str = RSAUtils.encrypt(aes_key, default_rsa_public_key); //rsa密文--公钥加密
        String md5_str = "";
        try {
            md5_str = MD5.digest(aes_key+ plantText);
        } catch (Exception e) {
            e.printStackTrace();
        }
        StringBuffer sb = new StringBuffer();
        sb.append(md5_str).append(RSAUtils.SEPARATOR).append(RSAUtils.SEPARATOR).append(aes_str).append(RSAUtils.SEPARATOR).append(RSAUtils.SEPARATOR).append(rsa_str);
        return sb.toString();
    }

    /**
     * 生成16位随机字符串
     * @return
     */
    public static final String getSeqNo(int len){
        String randomStr = "qwertyuiopasdfghjklzxcvbnm1234567890QWERTYUIOPASDFGHJKLZXCVBNM";
        StringBuilder stringBuilder = new StringBuilder();
        Random random = new Random();
        for (int i = 0; i < len; i++) {
            stringBuilder.append(randomStr.charAt(random.nextInt(randomStr.length())));
        }
        return stringBuilder.toString();
    }


}
